// 使用组件
layui.use(['layer', 'table', 'form'], function(){
  var layer = layui.layer;
  var table = layui.table;
  var form = layui.form;

  //加载数据
  table.render({
      elem: '#accountList'
      , url: 'admin-account/list/' //数据接口
      , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
      , page: {
          layout: ['count', 'prev', 'page', 'next', 'skip']
          , prev: '上一页'
          , next: '下一页'
          , limit: 10
      }
      , request: {
          pageName: 'pageNum' //页码的参数名称，默认：page
          , limitName: 'pageSize' //每页数据量的参数名，默认：limit
      }
      , parseData: function (res) { //res 即为原始返回的数据
          return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": res.data.total,
              "data": res.data.list, //解析数据列表
          };
      }
      , done: function (res, curr, count) {
          // 解决无数据table样式错乱
          if(count == 0){
              $("th[data-key='1-0-6']").css("border-right", "0");
          }
      }
      , cols: [[ //表头
          {type: 'checkbox'}
          , {field: 'username', title: '账号'}
          , {field: 'nickName', title: '姓名'}
          , {field: 'email', title: '邮箱'}
          , {field: 'registerTime', width: 170, title: '创建时间'}
          , {field: 'lastOnlineTime', width: 170, title: '最后在线时间'}
          , {
              field: 'status', title: '状态', width: 80, templet: function (d) {
                  var html = '';
                  switch(d.status) {
                      case 1:
                          html = '<span style="color:#5FB878">正常</span>';
                          break;
                      case 2:
                          html = '<span style="color:#FFB800">锁定</span>';
                          break;
                      case 3:
                          html = '<span style="color:#FF5722">禁用</span>';
                          break;
                      default:
                          html = '<span style="color:#1E9FFF">未知</span>';
                  }
                  return html;
              }
          }
          , {title: '操作', width: 260, toolbar: '#operates', fixed: 'right'}
      ]]
  });

  //监听工具条
  table.on('tool(accountList)', function (obj) {
      var data = obj.data;
      var layEvent = obj.event;
      if (layEvent === 'enable') { //启用
        $.ajax({
            type: "POST",
            url: "admin-account/enable/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg('操作成功', {icon: 6});
                    //同步更新缓存对应的值
                    obj.update({status: result.data});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
      } else if (layEvent === 'del') { //删除
          layer.confirm('确认删除账号吗？', function(index){
                layer.close(index);
                layer.load();
                $.ajax({
                    type: "POST",
                    url: "admin-account/delete/" + data.id,
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        layer.closeAll('loading');
                        if (result.code == 0) {
                            layer.msg('删除成功', {icon: 6});
                            obj.del(); //删除当前行
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
            });
      } else if (layEvent === 'reset') { //重置
          layer.prompt({formType: 1, title: "重置密码", placeholder:"请输入新密码", maxlength: 20}, function(value, index, elem){
              $.ajax({
                type: "POST",
                url: "admin-account/password/",
                data: {"id": data.id, "pwd": md5(value)},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg('重置成功', {icon: 6});
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
              });
              layer.close(index);
          });
      } else if (layEvent === 'update') { //修改
        var index = layer.open({
            type: 1,
            title: "修改管理员",
            area: windowWidth < 800 ? '370px' : '400px',
            content: $('#update-admin')
        });
        indexMap.set('#update-admin',index);
        //给表单赋值
        form.val("update-admin", {
            "id": data.id
            , "username": data.username
            , "email": data.email
            , "nickName": data.nickName
        });
      }
  });

  $("#search").click(function(){
      var name = $("#searchName").val();
      table.reload('accountList', {page: {curr: 1}, where: {"name": name}});
  });

  // 添加管理员
  $("#addBtn").click(function () {
      var index = layer.open({
          type: 1,
          title: "添加管理员",
          area: windowWidth < 800 ? '370px' : '400px',
          content: $('#add-admin')
      });
      indexMap.set('#add-admin',index);
      // 表单赋值
      form.val("add-admin", {
          "username": ""
          , "password": ""
          , "email": ""
          , "nickName": ""
      });
  });

  $("#cancelAddAdmin").click(function () {
      layer.close(indexMap.get('#add-admin'));
  });

  $("#cancelUpdateAdmin").click(function () {
        layer.close(indexMap.get('#update-admin'));
  });

  // 新增管理员
  form.on('submit(addAdmin)', function (data) {
      data.field.password = md5(data.field.password);
      layer.load();
      $.ajax({
          type: "POST",
          url: "admin-account/save",
          data: JSON.stringify(data.field),
          contentType: 'application/json;charset=utf-8',
          dataType: "json",
          headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
          success: function (result) {
              layer.closeAll('loading');
              layer.close(indexMap.get('#add-admin'));
              if (result.code == 0) {
                  window.location.reload();
              } else {
                  layer.msg(result.msg, {icon: 5});
              }
          }
      });
      return false;
  });

    // 修改管理员
    form.on('submit(updateAdmin)', function (data) {
        layer.load();
        $.ajax({
            type: "POST",
            url: "admin-account/save",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#update-admin'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

  form.verify({
      username: function (value, item) {
          if(!/^[0-9a-zA-Z_]{6,18}$/.test(value)){
              return '输入6~18个字符，字母、数字、下划线';
          }
          var msg;
          $.ajax({
              type: "GET",
              url: 'admin-account/username/' + value,
              async: false,
              dataType: 'json',
              headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
              success: function (result) {
                  if (result.data) {
                      msg = "账号已存在";
                  }
              }
          });
          return msg;
      },
      exitEmail: function (value, item) {
          var msg;
          $.ajax({
              type: "GET",
              url: 'admin-account/email/' + value,
              headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
              async: false,
              dataType: 'json',
              success: function (result) {
                  if (result.data) {
                      msg = "邮箱已被使用";
                  }
              }
          });
          return msg;
      },
      password: function (value, item) {
          if(!/^[0-9a-zA-Z_]{6,18}$/.test(value)){
            return '输入6~18个字符，字母、数字、下划线';
          }
      }
    });

  initSearch("#searchName");
});
